package com.itheima.handler;

import com.itheima.exception.LoginFailedException;
import com.itheima.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 处理唯一约束异常！
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e){
        e.printStackTrace();
        //TODO:: 请补充代码
        log.error("异常信息：{}", e.getMessage());
        String message = e.getMessage();
        if(message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String name = split[2];
            return Result.error(name + "用户已存在");
        }
        return Result.error("未知错误");
    }

    /**
     * 处理登录失败异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result handleLoginFailedException(LoginFailedException e){
        e.printStackTrace();
        return Result.error(e.getMessage());
    }

}
